const express = require('express');
const bcrypt = require('bcryptjs');
const User = require('../models/user');
const { pool } = require('../config/db');
const { authMiddleware, adminMiddleware } = require('../middleware/auth');

const router = express.Router();

// @route   GET api/users/profile
// @desc    Get user profile
// @access  Private
router.get('/profile', authMiddleware, async (req, res) => {
  try {
    const user = await User.findById(req.user.id);
    
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    
    res.json(user);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   PUT api/users/profile
// @desc    Update user profile
// @access  Private
router.put('/profile', authMiddleware, async (req, res) => {
  try {
    const { full_name, phone, address } = req.body;
    
    // Create user data object
    const userData = {
      full_name,
      phone,
      address
    };
    
    const updatedUser = await User.update(req.user.id, userData);
    res.json(updatedUser);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   PUT api/users/password
// @desc    修改用户密码
// @access  Private
router.put('/password', authMiddleware, async (req, res) => {
  try {
    const { current_password, new_password } = req.body;
    
    // 参数验证
    if (!current_password || !new_password) {
      return res.status(400).json({ 
        message: '当前密码和新密码都是必需的'
      });
    }

    // 密码长度验证
    if (new_password.length < 6) {
      return res.status(400).json({ 
        message: '新密码长度不能小于6个字符'
      });
    }

    // 获取用户信息
    const [rows] = await pool.query(
      'SELECT id, password FROM users WHERE id = ?', 
      [req.user.id]
    );
    
    const user = rows[0];
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    // 验证当前密码
    const isMatch = await bcrypt.compare(current_password, user.password);
    if (!isMatch) {
      return res.status(401).json({ message: '当前密码不正确' });
    }

    // 验证新密码不能与当前密码相同
    if (current_password === new_password) {
      return res.status(400).json({ 
        message: '新密码不能与当前密码相同'
      });
    }
    
    // 生成密码哈希
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(new_password, salt);
    
    // 更新密码
    await pool.query(
      'UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?',
      [hashedPassword, user.id]
    );
    
    res.json({ 
      message: '密码修改成功'
    });
  } catch (err) {
    console.error('修改密码失败:', err);
    res.status(500).json({ 
      message: '服务器错误，请稍后重试'
    });
  }
});

// @route   GET api/users/count
// @desc    获取用户总数
// @access  公开
router.get('/count', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT COUNT(*) as count FROM users');
    console.log('获取用户总数:', rows[0].count);
    res.json({ count: rows[0].count });
  } catch (err) {
    console.error('获取用户总数失败:', err);
    res.status(500).json({ message: '服务器错误' });
  }
});

// @route   GET api/users
// @desc    Get all users (admin only)
// @access  Private/Admin
router.get('/', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    // Simple implementation - in a real app, you'd want pagination
    const [rows] = await pool.query(
      'SELECT id, username, email, full_name, phone, address, is_admin, created_at FROM users'
    );
    
    res.json(rows);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/users/:id
// @desc    Get user by ID
// @access  Private
router.get('/:id', authMiddleware, async (req, res) => {
  try {
    const userId = req.params.id;
    
    // 验证用户权限
    if (!req.user.is_admin && req.user.id !== parseInt(userId)) {
      return res.status(403).json({ message: '没有权限访问其他用户的信息' });
    }
    
    console.log('获取用户信息 - 用户ID:', userId);
    console.log('当前用户:', req.user);
    
    const user = await User.findById(userId);
    
    if (!user) {
      return res.status(404).json({ message: '未找到该用户' });
    }
    
    // 不返回密码等敏感信息
    delete user.password;
    res.json(user);
  } catch (err) {
    console.error('获取用户信息失败:', err);
    res.status(500).json({ message: '服务器错误' });
  }
});

// @route   PUT api/users/:id
// @desc    Update user by ID (admin only)
// @access  Private/Admin
router.put('/:id', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const userId = req.params.id;
    const { email, full_name, phone, address } = req.body;
    
    // Check if user exists
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    
    // Update user using the model method
    const userData = { email, full_name, phone, address };
    const updatedUser = await User.adminUpdate(userId, userData);
    
    res.json(updatedUser);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   PUT api/users/:id/admin
// @desc    Toggle admin status for a user (admin only)
// @access  Private/Admin
router.put('/:id/admin', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const userId = req.params.id;
    const { is_admin } = req.body;
    
    // Validate request
    if (typeof is_admin !== 'boolean') {
      return res.status(400).json({ message: 'Invalid admin status' });
    }
    
    // Prevent self-demotion
    if (parseInt(userId) === req.user.id && !is_admin) {
      return res.status(400).json({ message: 'Cannot remove your own admin privileges' });
    }
    
    // Check if user exists
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    
    // Update admin status using the model method
    const updatedUser = await User.updateAdminStatus(userId, is_admin);
    
    res.json({ 
      message: 'Admin status updated successfully',
      user: updatedUser
    });
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   POST api/users
// @desc    Create a new user (admin only)
// @access  Private/Admin
router.post('/', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const { username, email, password, full_name, phone, address, is_admin } = req.body;
    
    // Validate required fields
    if (!username || !email || !password || !full_name) {
      const missingFields = [];
      if (!username) missingFields.push('username');
      if (!email) missingFields.push('email');
      if (!password) missingFields.push('password');
      if (!full_name) missingFields.push('full_name');
      
      return res.status(400).json({ 
        message: '缺少必填字段', 
        details: `缺少字段: ${missingFields.join(', ')}` 
      });
    }

    // Email format validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return res.status(400).json({ message: '邮箱格式无效' });
    }

    // Username validation
    if (username.length < 3 || username.length > 20) {
      return res.status(400).json({ message: '用户名长度必须在3到20个字符之间' });
    }

    // Password validation
    if (password.length < 6) {
      return res.status(400).json({ message: '密码长度不能小于6个字符' });
    }

    // Check if user already exists
    let existingUser = await User.findByEmail(email);
    if (existingUser) {
      return res.status(400).json({ message: '该邮箱已被注册' });
    }

    existingUser = await User.findByUsername(username);
    if (existingUser) {
      return res.status(400).json({ message: '用户名已被占用' });
    }
    
    // Create user with the provided data
    const userData = {
      username,
      email,
      password,
      full_name,
      phone: phone || null,
      address: address || null
    };
    
    // Create the user
    const newUser = await User.create(userData);
    
    // Set admin status if specified (default to false)
    if (is_admin) {
      await User.updateAdminStatus(newUser.id, true);
      newUser.is_admin = true;
    }
    
    res.status(201).json(newUser);
  } catch (err) {
    console.error('创建用户失败:', err.message);
    res.status(500).json({ message: '服务器错误', error: err.message });
  }
});

// @route   DELETE api/users/:id
// @desc    Delete a user (admin only)
// @access  Private/Admin
router.delete('/:id', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const userId = req.params.id;
    
    // Prevent self-deletion
    if (parseInt(userId) === req.user.id) {
      return res.status(400).json({ message: '不能删除自己的账户' });
    }
    
    // Check if user exists
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    // Delete the user
    await User.delete(userId);
    
    res.json({ message: '用户已成功删除' });
  } catch (err) {
    console.error('删除用户失败:', err.message);
    res.status(500).json({ message: '服务器错误', error: err.message });
  }
});

module.exports = router; 